<template>
	<view class="container">
		<!-- <button @click="nearby_search">搜索周边KFC</button> -->
		<map id="idMap" class="myMap" :customCallout="callout" :latitude="latitude" :longitude="longitude"
			:markers="markers" @poitap="poitap" show-location @callouttap="calloutTap">
			<cover-view slot="callout">
				<view v-for="(item,index) in markers">
					<cover-view :marker-id="item.id" :key='index'>
						<cover-view class="customCallout" :marker-id="item.id">
							<cover-image class="coverimage" :src='item.options.iconPath'></cover-image>
							<!-- <cover-view class="covername">{{ formatProductName(item.goodsname) }}</cover-view> -->
							<!-- <cover-view class="covername">{{ item.goodsdetail }}</cover-view> -->
						</cover-view>
					</cover-view>
				</view>
			</cover-view>
		</map>

		<!-- 搜索 start -->
		<view class="search-box">
			<view class="searchinputbox flex space-between">
				<input class="search-input" placeholder="请输入商品名称" @input="getsuggest" :value="searchKey"  />
				<view class="search-text" @click.stop="gosearch">搜索</view>
			</view>
		</view>

		<!-- 搜索 end -->

	</view>

</template>

<script>
	import {
		formatProductName
	} from "../../utils/common";

	var self, mapCtx
	import QQMapWX from '../../utils/qqmap-wx-jssdk'
	var qqmapsdk;
	export default {
		data() {
			return {
				mediaUrl: uni.$http.mediaUrl,
				distance: 0,
				// 坦克厂  33.002883,112.491943
				// 故宫 latitude: 39.91799, longitude: 116.397027,
				latitude: 33.002883,
				longitude: 112.491943,

				// 南阳理工学院(北门) 32.973723,112.549223
				// 菜鸟驿站(南阳市坦克厂家属院店) 33.002883,112.491943
				// 花花牛(坦克厂店) 32.995885,112.489748
				markers: [
					// {
					// 	id: 0,
					// 	latitude: 39.91799,
					// 	longitude: 116.397027,
					// 	// iconPath: '/static/img/state2.png', //显示的图标
					// 	rotate: 0, // 旋转度数
					// 	width: 20, //宽
					// 	height: 20, //高
					// 	title: 'A发布商品', //标注点名
					// 	alpha: 1, //透明度
					// 	joinCluster: true,
					// 	customCallout: {
					// 		anchorY: 0,
					// 		anchorX:0,
					// 		display: "ALWAYS",
					// 	},
					// 	count:100,
					// },
				],
				searchKey: '',
				s: '',
				obj: {},
				mediaUrl: uni.$http.mediaUrl,

			}
		},
		onLoad(e) {
			self = this
			// 获取当前map
			mapCtx = wx.createMapContext('idMap')
			// mapCtx.initMarkerCluster({ // 初始化点聚合的配置
			// 				        enableDefaultStyle: true, // 是否使用默认样式
			// 				        zoomOnClick: true,
			// 				        gridSize: 1,
			// 				        // complete(res) {
			// 				        //   console.log('initMarkerCluster', res)
			// 				        // }
			// 				});

			// 实例化API核心类
			qqmapsdk = new QQMapWX({
				key: this.wemapkey
			});
			self.s = e.searchKey
			
			console.log('onLoadsearchKey' + e.searchKey)
		},
		onShow() {
			this.getAuthorizeInfo()
			
		},
		methods: {
			formatProductName,
			// 触发关键词输入提示事件
			getsuggest: function(e) {
				self.searchKey = e.detail.value;
				
				// console.log(self.searchKey)
			},

			// 位置授权
			getAuthorizeInfo() {
				uni.authorize({
					scope: 'scope.userLocation',
					success() { // 允许授权
						self.getLocationInfo();
					},
					fail() { // 拒绝授权
						self.openConfirm();
						// console.log("你拒绝了授权，无法获得周边信息")
					}
				})
			},
			// 位置授权成功后，自动获取地理位置经纬度
			getLocationInfo() {
				uni.getLocation({
					type: 'gcj02',
					success(res) {
						console.log({
							icon: 'none',
							title: '当前位置:' + res.latitude + ',' + res.longitude
						})
						self.latitude = res.latitude;
						self.longitude = res.longitude;

						self.getMarkersList()
						// 直接跳到这个页面要么起始状态,要么
						

					}
				});
			},
			// 点击搜索按钮，跳转到新地址
			gosearch() {
				if(isNaN(self.searchKey)){
					console.log('不是数字')
				}else{
					console.log('是数字')
				}
				if (self.searchKey == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入'
					})
				} else {
					this.getMarkersList()
				}

			},
			//对搜到的商品比较距离，自动跳转到最近的一个商品
			cxClick() {
				var dest = [];
				for (var i = 0; i < this.markers.length; i++) {
					var obj = {}
					obj.latitude = parseFloat(this.markers[i].latitude)
					obj.longitude = parseFloat(this.markers[i].longitude)
					dest.push(obj)
				}
				var start = {
					latitude: parseFloat(this.latitude),
					longitude: parseFloat(this.longitude)
				};
				if (dest.length > 0) {
					console.log('有商品' + dest.length)
					qqmapsdk.calculateDistance({
						from: start,
						to: dest,
						success: function(res) {
							var res = res.result;
							var distance = res.elements[0].distance / 1000
							var obj = {
								latitude: res.elements[0].to.lat,
								longitude: res.elements[0].to.lng
							}
							for (var i = 0; i < res.elements.length; i++) {
								if (res.elements[i].distance / 1000 < distance) {
									distance = res.elements[i].distance / 1000
									obj.latitude = res.elements[i].to.lat
									obj.longitude = res.elements[i].to.lng
								}
							}
							self.distance = parseFloat(distance).toFixed(2)
							console.log(distance)

							self.toLocation(obj)
						},
						fail: function(error) {
							console.error(error);
						}
					});
				} else {
					console.log('无商品')
					uni.showToast({
						icon: 'none',
						title: '没有该类型商品'
					})
				}

			},
			// 获取商品列表
			async getMarkersList() {
				this.markers = []
				const postmsg = {
					searchKey: self.searchKey!=''?self.searchKey:self.s
				}
				const {
					data: res
				} = await uni.$http.post('getMarkersList/', postmsg)
				if (res.code == 200) {
					for (let i = 0; i < res.data.length; i++) {
						var obj = {}
						obj.id = i
						obj.goodsid = res.data[i].goodsid
						obj.latitude = res.data[i].latitude
						obj.longitude = res.data[i].longitude
						obj.address = res.data[i].address
						obj.goodsname = res.data[i].goodsname
						obj.date = res.data[i].date
						obj.imagelist = JSON.parse(res.data[i].imagelist);
						// iconPath: '/static/images/map/none.png',
						obj.options = {
								iconPath: obj.imagelist[0],
								// nickname: unescape(res.data[i].nickname),
								nickname: res.data[i].nickname,
								username: res.data[i].username,
							},
							obj.rotate = 0 //旋转角度
						obj.width = 20
						obj.height = 20
						obj.title = res.data[i].goodsname //点击时显示
						obj.goodsdetail = res.data[i].goodsdetail
						obj.alpha = 1 //透明度
						obj.joinCluster = false //参与点聚合
						obj.customCallout = { //自定义气泡
							anchorY: 0,
							anchorX: 0,
							display: "ALWAYS",
						}
						// obj.count = res.datalist[i].count
						obj.count = 1
						this.markers.push(obj)
					}
					// 如果有关键字才跳转,否则只显示自己的位置
					if (self.searchKey!='') {
						this.cxClick()
					}
					
				} else {
					console.log(res.msg);
				}
			},


			// 再次获取授权，当用户第一次拒绝后再次请求授权
			openConfirm() {
				uni.showModal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置，请确认授权',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting(); // 打开地图权限设置
						} else if (res.cancel) {
							uni.showToast({
								title: '您拒绝了授权，无法获得周边信息',
								icon: 'none',
								duration: 3000
							})
						}
					}
				});
			},

			// 位置跳转程序
			toLocation: function(obj) {
				// 改变地图中心位置
				mapCtx.moveToLocation(obj)
				// 移动标记点并添加动画效果
				// mapCtx.translateMarker({
				//   markerId: 0,
				//   autoRotate: true,
				//   duration: 100,
				//   destination: {
				//     latitude:obj.latitude,
				//     longitude:obj.longitude,
				//   },
				//   animationEnd() {
				//     // console.log('animation end')
				//   }
				// })
			},

			// 鼠标拖动点击兴趣地点，位置地图跳转
			poitap: function(e) {
				var obj = e.detail
				// console.log(e.detail)
				// uni.showToast({ icon: 'none', title: 'POITap:'+e.detail})
				self.toLocation(obj)
			},

			calloutTap(e) {

				const {
					markerId
				} = e.detail;
				const marker = this.markers.find((m) => m.id === markerId);
				console.log(marker.goodsid)
				// // var msg = '商品名字:'+marker.title+','+
				// //           '商品老板:'+marker.options.username+','+
				// // 		  '联系方式:'+marker.options.phone+','+
				// // 		  '商品ID:'+marker.goodsid
				// // uni.showToast({ icon:'none', title: msg})
				// uni.navigateTo({
				// 	url: '/pages/home/goodsdetail?username='+marker.options.username+'&juli='+this.distance+
				// 	'&userid='+marker.options.userid+'&phone='+marker.options.phone+'&goodsid='+marker.goodsid+
				// 	'&goodsname='+marker.title+'&goodsdetail='+marker.goodsdetail+
				// 		 '&image='+marker.options.iconPath+'&imagelist='+marker.imagelist+
				// 		 '&date='+marker.date+'&address='+marker.address+'&latitude='+marker.latitude+'&longitude='+marker.longitude
				// })
				uni.navigateTo({
					url: '/pages/home/goodsdetail?goodsid=' + marker.goodsid
				})
			},
		},
	}
</script>

<style lang="scss">
	.container {
		padding: 0;
		height: 100vh;
	}

	.myMap {
		width: 100%;
		height: 100%;

		.customCallout {
			// background-color: #0099cc;
			display: flex;
			flex-direction: column;

			// justify-content: center;
			// align-items: center;
			// box-sizing: border-box;
			.coverimage {
				background-color: #e29233;
				border-radius: 10px;
				width: 120rpx;
				height: 120rpx;
				// image{
				// 	width: 100rpx;
				// 	height: 100rpx;
				// }
			}

			.covername {
				font-size: 22rpx;
				color: #e29233;
				text-align: center;
				line-height: 1.5;
			}
		}
	}

	/* 搜索框 */
	.search-box {
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		background-color: #6C64D0;
		position: fixed;
		width: 100%;
		box-sizing: border-box;
		left: 0;
		top: 0;
	}

	.searchinputbox {
		// background-color: rebeccapurple;
		background-color: #fff;
		border: 4rpx solid #9692D6;
		border-radius: 70rpx;
		flex: 1;

		.search-input {
			height: 63rpx;
			line-height: 63rpx;
			padding: 0 20rpx;
			flex: 1;
			box-sizing: border-box;


		}

		.search-text {
			color: #ffffff;
			background-color: #6C64D0;
			border-radius: 50rpx;
			width: 90rpx;
			line-height: 72rpx;
			text-align: center;
			font-size: 24rpx;
			text-align: center;

		}
	}
</style>